// 封装购物车模块

import { defineStore } from 'pinia'
import { ref,computed } from 'vue'
import { useUserStore } from './user'

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  // 1. 定义state - cartList
  const cartList = ref([])

  // 2. 定义action - addCart
  const addCart = (goods) => {
    // 添加购物车操作
    // 已添加过 - count + 1
    // 没有添加过 - 直接push
  return new Promise((resolve, reject) => {
    if(userStore.userInfo.token){
      const item = cartList.value.find((item) => goods.id === item.id)
      if (item) {
        // 找到了
        item.count++
      } else {
        // 没找到
        cartList.value.push(goods)
      }
      resolve({
        code: 200
      })
     }else{
      resolve({
        code: 401
      })
     }
    }
  )}


  const updateNewList = () => {
    cartList.value = cartList.value.filter(item => !item.selected)
  }


  const allCount = computed(() => {
    return cartList.value.reduce((pre, item) => pre + item.count, 0)
  })

  const allPrice = computed(() => {
    return cartList.value.reduce((pre, item) => pre + item.price * item.count, 0)
  })

  const delCart = async(id) => {

      const index = cartList.value.findIndex(item => item.id === id)
      if (index !== -1) {
        cartList.value.splice(index, 1)
      }

  }
  const singleCheck = (id, selected) => {
    const item = cartList.value.find(item => item.id === id)
    item.selected = selected
  }

  // 3. 已选择数量 filter过滤返回数组
const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
// 4. 已选择商品价钱合计
const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))

  return {
    cartList,
    allCount,
    allPrice,
    selectedCount,
    selectedPrice,

    addCart,
    delCart,
    singleCheck,
    updateNewList
  }
}, {
  persist: true,
})
